<?php
class Mageex_RelatedProduct_Helper_Data extends Mage_Core_Helper_Abstract
{
	public function getArrAttribute()
	{
		$arrCode = array();	
		
		$collection = Mage::getResourceModel('eav/entity_attribute_collection')
									->setEntityTypeFilter( Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId())
									->addFilter("is_visible", 1)
									->addFilter("is_filterable", 1);
		
		foreach($collection->getItems() as $col) {
			$arrCode[] = $col->getAttributeCode();
		}
		return $arrCode;
	}
	public function getRelatedProduct($currentProduct, $arrNotIn = array())
	{	
		if($currentProduct){
			$id = $currentProduct->getId();
			
			array_push($arrNotIn, $id);
			
			$_product = Mage::getModel('catalog/product')->load($id);
			
			/*get child category*/
			$cate = $_product->getCategoryCollection();

			$visibility = array(
					Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
					Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG
			);
			
			$_related = Mage::getModel('catalog/product')->getCollection()
				  ->addAttributeToSelect('*')
				  ->addAttributeToFilter('visibility', $visibility)
				  ->addAttributeToFilter('entity_id', array('nin' => $arrNotIn))
				  ->addAttributeToSelect('small_image');
				  
			foreach($cate as $top){
				//add category to filter related collection
				
				$_related->addCategoryFilter($top);
			}
			if(Mage::helper('relatedproduct/config')->getRelatedSelect() == 'random'){
				//set random order for related collection
				
				$_related->getSelect()->order(new Zend_Db_Expr('RAND()'));
			}
			//set limit product on relate;
			$numberItems = Mage::helper('relatedproduct/config')->getRelatedNumberItems();
			$_related->setPage(1, $numberItems);
			
			//special_price
			/** get array of attribute code **/
			//$arrCode = $this->getArrAttribute();
			$attribute = Mage::helper('relatedproduct/config')->getRelatedApplyPrice();
			$operator = Mage::helper('relatedproduct/config')->getRelatedOperator();
			$value = Mage::helper('relatedproduct/config')->getRelatedPriceValue();
			$_related->addAttributeToFilter($attribute, array($operator=>$value));
			
			return $_related;
		}
	}
	public function loadAttributeOptions()
	{
		$productAttributes = Mage::getResourceSingleton('catalog/product')
			->loadAllAttributes()
			->getAttributesByCode();

		$attributes = array();
		foreach ($productAttributes as $attribute) {
			/* @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
			if (!$attribute->isAllowedForRuleCondition()) {
				continue;
			}
			$attributes[$attribute->getAttributeCode()] = $attribute->getFrontendLabel();
		}
		return $attributes;
	}
	public function getProductFromConditions($data)
	{
		$modelRule = Mage::getModel('relatedproduct/rule');
		$data['conditions'] = $data['rule']['conditions'];
		unset($data['rule']);

		$modelRule->loadPost($data);
		
		//$model->getData();
		
		// Serialize conditions data
		$dataSerialized = serialize($modelRule->getConditions()->asArray());
		$websiteIds = array();
		$productCollection = Mage::getResourceModel('catalog/product_collection');
		//Get Website Id
		if($data['stores'][0] !=0){
			foreach($data['stores'] as $key=>$store_id){
				$websiteIds[] = Mage::getModel('core/store')->load($store_id)->getWebsiteId();
			}
			$productCollection->addWebsiteFilter($websiteIds);
		}
		$_rule = Mage::getModel('rule/rule')->getConditions();
		
		$modelRule->getConditions()->collectValidatedAttributes($productCollection);

		Mage::getSingleton('core/resource_iterator')->walk(
			$productCollection->getSelect(),
			array(array($modelRule, 'callbackValidateProduct')),
			array(
				'attributes' => $modelRule->getCollectedAttributes(),
				'product'    => Mage::getModel('catalog/product'),
			)
		);

		return $modelRule->getProductIds();
	}
	public function getBlockIdsToOptionsArray()
	{
		return array(
            array(
                'label' => $this->__('Catalog and product'),
                'value' => array(
                    array('value' => 'catalog-sidebar-right-top',   'label' => $this->__('Catalog Sidebar Right Top')),
                    array('value' => 'catalog-sidebar-right-bottom','label' => $this->__('Catalog Sidebar Right Bottom')),
                    array('value' => 'catalog-sidebar-left-top',    'label' => $this->__('Catalog Sidebar Left Top')),
                    array('value' => 'catalog-sidebar-left-bottom', 'label' => $this->__('Catalog Sidebar Left Bottom')),
                    array('value' => 'catalog-content-top',         'label' => $this->__('Catalog Content Top')),
                    array('value' => 'catalog-menu-top',            'label' => $this->__('Catalog Menu Top')),
                    array('value' => 'catalog-menu-bottom',         'label' => $this->__('Catalog Menu Bottom')),
                    array('value' => 'catalog-page-bottom',         'label' => $this->__('Catalog Page Bottom')),
                )),
            array(
                'label' => $this->__('Product only'),
                'value' => array(
                    array('value' => 'product-sidebar-right-top',   'label' => $this->__('Product Sidebar Right Top')),
                    array('value' => 'product-sidebar-right-bottom','label' => $this->__('Product Sidebar Right Bottom')),
                    array('value' => 'product-sidebar-left-top',    'label' => $this->__('Product Sidebar Left Top')),
                    array('value' => 'product-sidebar-left-bottom', 'label' => $this->__('Product Sidebar Left Bottom')),
                    array('value' => 'product-content-top',         'label' => $this->__('Product Content Top')),
                    array('value' => 'product-menu-top',            'label' => $this->__('Product Menu Top')),
                    array('value' => 'product-menu-bottom',         'label' => $this->__('Product Menu Bottom')),
                    array('value' => 'product-page-bottom',         'label' => $this->__('Product Page Bottom')),
                ))
        );
	}
	public function _getDaySeconds($hours, $minutes, $seconds)
	{
		return $hours*3600 + $minutes*60 + $seconds;
	}
	public function getBlocks($position, $type, $getPosition=false)
	{
		
		$arrPosition = array();
		$arrItems	 = array();
		$collection = Mage::getResourceModel('relatedproduct/relatedproduct_collection');

        $collection->getSelect()
            ->where('status=1')
            ->where('find_in_set(0, stores) OR find_in_set(?, stores)', (int)(Mage::app()->getStore()->getId()))
            ->order('priority');
		if($position){
			$collection->getSelect()->where('position=?', $position);
		}
		if($type){
			$collection->getSelect()->where('type=?', $type);
		}
		//echo $collection->getSelect();
		
		// time check

        $timestamp = Mage::getModel('core/date')->timestamp();
        $time = getdate($timestamp);

        $daySecondsNow = $this->_getDaySeconds($time['hours'], $time['minutes'], $time['seconds']);
        $today = $timestamp - $daySecondsNow; // in seconds
		
		
		foreach($collection->getItems() as $item)
        {
			
			if(($item->getDateStart() && $today < strtotime($item->getDateStart()))
            ||
            ($item->getDateExpire() && $today > 1+strtotime($item->getDateExpire()))){
				
			}else{
				$arrItems[] = $item;
				$arrPosition[] = $item->getPosition();
			}
			
		}
		if($getPosition){
			return $arrPosition;
		}
		return $arrItems;
	}
}